package com.elric.mall.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.elric.mall.common.utils.ImportExcelUtil;
import com.elric.mall.dto.DictionaryImportDto;
import com.elric.mall.dto.ZgBaseNltxNode;
import com.elric.mall.dto.ZgProvincesNode;
import com.elric.mall.enums.ImportType;
import com.elric.mall.mapper.*;
import com.elric.mall.model.*;
import com.elric.mall.service.DictionaryService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 实现功能：字典表实现层
 *
 * @author 作者[Yuxuan.he]
 * @version 1.0.00  2021-09-16 11:21
 */
@Service
public class DictionaryServiceImpl implements DictionaryService {
    @Autowired
    private DictionaryMapper dictionaryMapper;

    @Autowired
    private ZgBaseInfoMapper zgBaseInfoMapper;

    @Autowired
    private ZgBaseNltxMapper zgBaseNltxMapper;

    @Autowired
    private ZgSProvincesMapper zgSProvincesMapper;

    private void init(Dictionary dictionary) {
        dictionary.setId(IdUtil.fastUUID());
        dictionary.setCreateTime(new DateTime());
        dictionary.setUpdateTime(new DateTime());
    }

    @Override
    public int create(Dictionary dictionary) {
        init(dictionary);
        return dictionaryMapper.insert(dictionary);
    }

    @Override
    public int update(Dictionary dictionary) {
        dictionary.setUpdateTime(new DateTime());
        return dictionaryMapper.updateByPrimaryKeySelective(dictionary);
    }

    @Override
    public Dictionary findById(String id) {
        return dictionaryMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Dictionary> findByType(String type) {
        DictionaryExample example = new DictionaryExample();
        example.createCriteria().andTypeEqualTo(type);
        example.setOrderByClause("order_num asc");
        return dictionaryMapper.selectByExample(example);
    }

    @Override
    public List<ZgBaseInfo> findZgDictByType(String type) {
        ZgBaseInfoExample example = new ZgBaseInfoExample();
        example.createCriteria().andTypeEqualTo(type);
        example.setOrderByClause("order_number asc");
        return zgBaseInfoMapper.selectByExample(example);
    }

    /**
     * 将nltx实体转化为树形结构
     */
    private ZgBaseNltxNode covertNltxNode(ZgBaseNltx base, List<ZgBaseNltx> menuList) {
        ZgBaseNltxNode node = new ZgBaseNltxNode();
        BeanUtils.copyProperties(base, node);
        node.setTitle(node.getText());
        List<ZgBaseNltxNode> children = menuList.stream()
                .filter(subMenu -> StrUtil.equals(subMenu.getParentInfoId(), base.getId()))
                .map(subMenu -> covertNltxNode(subMenu, menuList)).collect(Collectors.toList());
        node.setChildren(children);
        return node;
    }

    @Override
    public List<ZgBaseNltxNode> findNltxTree(String tableName) {
        List<ZgBaseNltx> list = zgBaseNltxMapper.selectCommon(tableName);
        List<ZgBaseNltxNode> result = list.stream()
                .filter(r -> StrUtil.isBlank(r.getParentInfoId()))
                .map(r -> covertNltxNode(r, list)).collect(Collectors.toList());
        return result;
    }

    /**
     * 将行政区划实体转化为树形结构
     */
    private ZgProvincesNode covertProvincesNode(ZgSProvinces base, List<ZgSProvinces> menuList) {
        ZgProvincesNode node = new ZgProvincesNode();
        BeanUtils.copyProperties(base, node);
        node.setLabel(node.getCityName());
        node.setValue(node.getId());
        List<ZgProvincesNode> children = menuList.stream()
                .filter(subMenu -> StrUtil.equals(subMenu.getParentId(), base.getId()))
                .map(subMenu -> covertProvincesNode(subMenu, menuList)).collect(Collectors.toList());
        node.setChildren(children);
        return node;
    }

    @Override
    public List<ZgProvincesNode> findProvincesTree() {
        ZgSProvincesExample example = new ZgSProvincesExample();
        example.setOrderByClause("id desc");
        List<ZgSProvinces> list = zgSProvincesMapper.selectByExample(example);
        List<ZgProvincesNode> result = list.stream()
                .filter(r -> StrUtil.isBlank(r.getParentId()))
                .map(r -> covertProvincesNode(r, list)).collect(Collectors.toList());
        return result;
    }

    @Override
    public int delete(String id) {
        return dictionaryMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<Dictionary> list(Integer pageSize, Integer pageNum, Dictionary dictionary) {
        PageHelper.startPage(pageNum, pageSize);
        DictionaryExample example = new DictionaryExample();
        if(!StringUtils.isEmpty(dictionary.getName())) {
            example.createCriteria().andNameLike("%"+dictionary.getName()+ "%");
        }
        if(!StringUtils.isEmpty(dictionary.getType())) {
            example.createCriteria().andTypeEqualTo(dictionary.getType());
        }
        return dictionaryMapper.selectByExample(example);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<DictionaryImportDto> importDocuments(MultipartHttpServletRequest request) {
        return ImportExcelUtil.readExcelByRequest(request, new DictionaryImportDto());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertBatch(List<Dictionary> list, ImportType importType) {
        if (importType == ImportType.full) {
            DictionaryExample example = new DictionaryExample();
            dictionaryMapper.deleteByExample(example);
        }
        list.stream().forEach(d -> {
           init(d);
        });
        return dictionaryMapper.insertBatch(list);
    }
}
